package action.util;

import java.util.ArrayList;
import java.util.List;

import action.pojo.LANConnect;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class LANConnectSQLITE {
	private SQLiteDatabase database;
	private DatabaseHelper helper;
	
	String[] allColumnsServer = {DatabaseHelper.COLUMN_ID_LAN,DatabaseHelper.COLUMN_NAME_SERVER_LAN,
			DatabaseHelper.COLUMN_USERNAME_LAN,DatabaseHelper.COLUMN_PASSWORD_LAN};
	
	LANConnect lanConnect;
	
	public LANConnectSQLITE(Context context){
		helper = new DatabaseHelper(context);
	}
	
	public void open(){
		try {
			database = helper.getWritableDatabase();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void close(){
		helper.close();
	}
	
	// TODO begin create LAN server part
	
	public LANConnect createLANConnect(String nameserver,String username,String password){
		ContentValues values = new ContentValues();
		values.put(DatabaseHelper.COLUMN_NAME_SERVER_LAN, nameserver);
		values.put(DatabaseHelper.COLUMN_USERNAME_LAN, username);
		values.put(DatabaseHelper.COLUMN_PASSWORD_LAN, password);
		
		long insertId = database.insert(DatabaseHelper.TABLE_LAN_SERVER, null,
				values);
		Cursor cursor = database.query(DatabaseHelper.TABLE_LAN_SERVER,
				allColumnsServer, DatabaseHelper.COLUMN_ID_LAN + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		
		LANConnect newLanConnect = cursorToLan(cursor);
		cursor.close();
		return newLanConnect;
	}
	
	public List<LANConnect> getAllLANConnect(){
		List<LANConnect> lanConnects = new ArrayList<LANConnect>();
		
		Cursor cursor = database.query(DatabaseHelper.TABLE_LAN_SERVER,
				allColumnsServer, null, null, null, null, null);

		cursor.moveToFirst();
		while(!cursor.isAfterLast()){
			lanConnect = cursorToLan(cursor);
			lanConnects.add(lanConnect);
			cursor.moveToNext();
		}
		cursor.close();
		return lanConnects;
	}
	
	public LANConnect cursorToLan(Cursor cursor){
		lanConnect = new LANConnect();
		try {
			lanConnect.setIdLan(cursor.getInt(0));
			lanConnect.setServerNameLan(cursor.getString(1));
			lanConnect.setUsernameLan(cursor.getString(2));
			lanConnect.setPasswordLan(cursor.getString(3));
		} catch (Exception e) {
		}
		
		return lanConnect;
	}
}
